package com.dmgis.qxfw.dataservice.businessservice.yyhb.controller;

import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.common.pojo.AirPolRegForecast;
import com.dmgis.qxfw.dataservice.businessservice.common.pojo.TownshipForecast;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.WebCtrlData;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.yyhb.service.InteractiveConsultationServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/xthb")
public class InteractiveConsultationController {
	private  final String operatingSystem;

	@Autowired
	public InteractiveConsultationController(String operatingSystem) {
		this.operatingSystem = operatingSystem;
	}
	@Autowired
	private InteractiveConsultationServiceI serviceI;

	MongoService1 mongoService=new MongoService1();
	

	/**
	 * 下载精细化预报图片
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getPicture")
	@ResponseBody
	public Object getPicture(HttpServletRequest request, Model model) {
		String datechar = request.getParameter("startTime").substring(0, 10);// 日期
		String timechar = request.getParameter("startTime").substring(11, 13);//时效
		String ntimes = request.getParameter("ntimes");// 时次
		String type = request.getParameter("type");// 类型
		String types = "";
		String collectionName = "";
		if(type.contains("降水量")){
			types="rain";
			collectionName = "yb_rain_png_file";
		}
		if(type.contains("最高温")){
			types="maxtemp";
			collectionName = "yb_temp_png_file";
		}
		if(type.contains("最低温")){
			types="mintemp";
			collectionName = "yb_temp_png_file";
		}
		if(type.contains("气压")){
			types="press";
			collectionName = "yb_press_png_file";
		}
		if(type.contains("风速")){
			types="wind";
			collectionName = "yb_wind_png_file";
		}
		if(type.contains("湿度")){
			types="humidity";
			collectionName = "yb_humid_png_file";
		}
		String resultpath = "";
		String urlpath ;
		if (operatingSystem.equals("Windows")){
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Picture\\";// 临时文件目录
		}else {
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Picture/";// 临时文件目录
		}

		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
		String fileName = datechar + "_" + timechar + "_" + types + "_" + ntimes +".png";
		String servicePath = urlpath + fileName;// 服务器文件
		File serviceFile = new File(servicePath);// 服务器文件
		if (serviceFile.exists()) {// 把文件上传到服务器
			if (operatingSystem.equals("Windows")){
				resultpath = "Temp\\Picture\\" + fileName;
			}else {
				resultpath = "Temp/Picture/" + fileName;
			}

		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("datechar", datechar);
			map.put("timechar", timechar);
			map.put("ntimes", ntimes);
			map.put("type", type);
			map.put("collectionName", collectionName);
			map.put("advCode", DbConfig.advCode);
			byte[] data = mongoService.selectData(map);
			if(data == null){
				return "";
			}
			FileUtil.bytesToFile(data, servicePath);
			if (operatingSystem.equals("Windows")){
				resultpath = "Temp\\Picture\\" + fileName;
			}else {
				resultpath = "Temp/Picture/" + fileName;
			}
		}
		resultpath = resultpath.replace("\\", "/");
		return resultpath;
	}

	/**
	 * 获得精细化预报图片
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getlayerPicture")
	@ResponseBody
	public Object getlayerPicture(HttpServletRequest request, Model model) {
		String datechar = request.getParameter("startDate").substring(0, 10);// 日期
		String timechar = request.getParameter("startDate").substring(11, 13);//时效
		//String ntimes = request.getParameter("ntimes");// 时次
		String type = request.getParameter("element");// 类型
		String types = "";
		String[] ntimes = {"012","024","036","048","060","072","084","096","108","120","132","144","156","168"};
		String collectionName = "";
		List<String> result = new ArrayList<String>();
		if(type.contains("降水量")){
			types="rain";
			collectionName = "yb_rain_png_file";
		}
		if(type.contains("最高温")){
			types="maxtemp";
			collectionName = "yb_temp_png_file";
		}
		if(type.contains("最低温")){
			types="mintemp";
			collectionName = "yb_temp_png_file";
		}
		if(type.contains("气压")){
			types="press";
			collectionName = "yb_press_png_file";
		}
		if(type.contains("风速")){
			types="wind";
			collectionName = "yb_wind_png_file";
		}
		if(type.contains("湿度")){
			types="humidity";
			collectionName = "yb_humid_png_file";
		}
		for(int k=0;k<ntimes.length;k++){
			String resultpath = "";
			String urlpath ;
			if (operatingSystem.equals("Windows")){
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Picture\\";// 临时文件目录
			}else {
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Picture/";// 临时文件目录
			}

			FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
			FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
			String fileName = datechar + "_" + timechar + "_" + types + "_" + ntimes[k] +".png";
			String servicePath = urlpath + fileName;// 服务器文件
			File serviceFile = new File(servicePath);// 服务器文件
			if (serviceFile.exists()) {// 把文件上传到服务器
				if (operatingSystem.equals("Windows")){
					resultpath = "Temp\\Picture\\" + fileName;
				}else {
					resultpath = "Temp/Picture/" + fileName;
				}

			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("datechar", datechar);
				map.put("timechar", timechar);
				map.put("ntimes", ntimes[k]);
				map.put("type", type);
				map.put("collectionName", collectionName);
				map.put("advCode", DbConfig.advCode);
				byte[] data = mongoService.selectData(map);
				if(data == null){
					resultpath = "../../../images/nopic.jpg";
				}else{
					FileUtil.bytesToFile(data, servicePath);
					if (operatingSystem.equals("Windows")){
						resultpath = "Temp\\Picture\\" + fileName;
					}else {
						resultpath = "Temp/Picture/" + fileName;
					}
				}
			}
			resultpath = resultpath.replace("\\", "/");
			result.add(resultpath);
		}
		return result;
	}

	/**
	 * 图形成品  精细化预报图片下载
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getlayerProductPicture")
	@ResponseBody
	public Object getlayerProductPicture(HttpServletRequest request, Model model) {
		String datechar = request.getParameter("startDate").substring(0, 10);// 日期
		String timechar = request.getParameter("times");//时效
		String type = request.getParameter("element");// 类型
		String types = "";
		String[] ntimes = {"012","024","036","048","060","072","084","096","108","120","132","144","156","168"};
		String collectionName = "";
		List<String> result = new ArrayList<String>();
		if(type.contains("降水量")){
			types="rain";
			collectionName = "yb_rain_png_file";
		}
		if(type.contains("最高温")){
			types="maxtemp";
			collectionName = "yb_temp_png_file";
		}
		if(type.contains("最低温")){
			types="mintemp";
			collectionName = "yb_temp_png_file";
		}
		if(type.contains("气压")){
			types="press";
			collectionName = "yb_press_png_file";
		}
		if(type.contains("风速")){
			types="wind";
			collectionName = "yb_wind_png_file";
		}
		if(type.contains("湿度")){
			types="humidity";
			collectionName = "yb_humid_png_file";
		}
		for(int k=0;k<ntimes.length;k++){
			String resultpath = "";
			String urlpath ;
			if (operatingSystem.equals("Windows")){
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Picture\\";// 临时文件目录
			}else {
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Picture/";// 临时文件目录
			}

			FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
			FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
			String fileName = datechar + "_" + timechar + "_" + types + "_" + ntimes[k] +".png";
			String servicePath = urlpath + fileName;// 服务器文件
			// File localFile = new File(localPath);// 本地文件
			File serviceFile = new File(servicePath);// 服务器文件
			if (serviceFile.exists()) {// 把文件上传到服务器
				if (operatingSystem.equals("Windows")){
					resultpath = "Temp\\Picture\\" + fileName;
				}else {
					resultpath = "Temp/Picture/" + fileName;
				}

			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("datechar", datechar);
				map.put("timechar", timechar);
				map.put("ntimes", ntimes[k]);
				map.put("type", type);
				map.put("collectionName", collectionName);
				map.put("advCode", DbConfig.advCode);
				byte[] data = mongoService.selectData(map);
				if(data == null){
					resultpath = "../../../images/nopic.jpg";
				}else{
					FileUtil.bytesToFile(data, servicePath);
					if (operatingSystem.equals("Windows")){
						resultpath = "Temp\\Picture\\" + fileName;
					}else {
						resultpath = "Temp/Picture/" + fileName;
					}
				}
			}
			resultpath = resultpath.replace("\\", "/");
			result.add(resultpath);
		}
		return result;
	}


	/**
	 * 产品生成查询最新时间
	 * @return
	 */
	@RequestMapping("/productInitTime")
	@ResponseBody
	public String productInitTime(){
		Date date = serviceI.productInitTime();
		DateTime dt = new DateTime(date);
		return dt.toDateString();
	}

	/**
	 * 查询产品生成
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/proGen")
	@ResponseBody
	public String proGen(HttpServletRequest request) throws Exception{
		String startTime = request.getParameter("startTime");
		String time = request.getParameter("time");
		DateTime dateTime = DateTime.parseDate(startTime);
		int day = dateTime.GetDay();
		
		//未来七天空气质量预报
		String airInfo = "";
		List<AirPolRegForecast> aList =new ArrayList<AirPolRegForecast>();
		aList = serviceI.getAirInfo(startTime);
		if(aList.size()>0){
			for(AirPolRegForecast ap : aList){
				int i = Integer.valueOf(ap.getForecastType())/24;
				String dt = dateTime.AddDays(i).toDateString();
				airInfo += "    "+(day+(i-1)) + "日" + time + "时至" + (day+i) + "日" + time 
						+ "时  AQI指数:" + ap.getAQI() + ",PM2.5浓度为:" + ap.getPM2p5()
						+ ",PM10浓度为:" + ap.getPM10() + ",臭氧一小时浓度为:" + ap.getO3_1H()
						+ ",臭氧八小时浓度为:" + ap.getO3_8H() + "\n";
			}
		}else{
			airInfo += "    暂无数据！";
		}
		
		//未来七天天气预报
		String temp = "";
		String weather = "";
		float minWindS = 0;
		float maxWindS = 0;
		float minWindD = 0;
		float maxWindD = 0;
		String windD = "";
		String windS = "";
		String sevenWeather="";
		List<TownshipForecast> t = new ArrayList<TownshipForecast>();
		int[] ntime = {24,48,72,96,120,144,168};
		String cityStation = DbConfig.STATIONID;
		boolean b = false;
		if(DateTime.now().AddDays(-30).after(dateTime)){
			//ForecastInfoTemp
			b = true;
		}
		
		for(int i:ntime){
			t = serviceI.getWeatherForecasts(startTime, time, i, i-12, cityStation);
			if(t!=null&&t.size()>0){
				//温度
				if(t.get(0).getMaxTemp()==0&&t.get(0).getMinTemp()==0){
					return null;
				}else{
					temp = t.get(0).getMinTemp() + "～" + t.get(0).getMaxTemp() + "℃";
				}
				//天气现象1
				if(t.get(0).getWeather1().trim().equals(t.get(0).getWeather2())){
					weather = t.get(0).getWeather2();
				}else{
					weather = t.get(0).getWeather1() + "转" + t.get(0).getWeather2();
				}
				WebCtrlData wcd = new WebCtrlData();
				//风向
				if(!Float.valueOf(t.get(0).getWindD()).isNaN()){
					minWindD = t.get(0).getWindD();
				}
				if(!Float.valueOf(t.get(0).getWindD2()).isNaN()){
					maxWindD = t.get(0).getWindD2();
				}
				if(minWindD==maxWindD){
					windD = wcd.GetAllFx(String.valueOf(maxWindD));
				}else{
					windD = wcd.GetAllFx(String.valueOf(minWindD))+"转"+wcd.GetAllFx(String.valueOf(maxWindD));
				}
				//风速
				if(!Float.valueOf(t.get(0).getWindS()).isNaN()){
					minWindS = t.get(0).getWindS();
				}
				if(!Float.valueOf(t.get(0).getWindS2()).isNaN()){
					maxWindS = t.get(0).getWindS2();
				}
				if(minWindS==maxWindS){
					windS = String.valueOf(maxWindS);
				}else{
					windS = String.valueOf(minWindS)+"～"+String.valueOf(maxWindS);
				}
				int j = i/24;
				sevenWeather +=  "    "+(day+(j-1)) + "日" + time + "时至" + (day+j) + "日" + time
						+"时天气现象："+ weather + ",温度:"+temp+",风向:"+ windD +",风速："+windS+ "\n";
			}else{
				sevenWeather =  "    暂无数据！";
			}
		}
		String forecast = airInfo+"|"+sevenWeather;
		return forecast;
	}
}
